# SchedulerAI Backend Docker Image
# Multi-stage build for optimized production image

# Build arguments
ARG BUILD_DATE
ARG VCS_REF
ARG VERSION=latest

# ============================================================================
# Stage 1: Base Image Layer
# ============================================================================
FROM python:3.9-slim as base

# Add metadata labels
LABEL maintainer="SchedulerAI Team" \
      org.label-schema.name="SchedulerAI Backend" \
      org.label-schema.description="Project scheduling optimization API service" \
      org.label-schema.version="${VERSION}" \
      org.label-schema.build-date="${BUILD_DATE}" \
      org.label-schema.vcs-ref="${VCS_REF}" \
      org.label-schema.schema-version="1.0"

# Set environment variables for Python
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PYTHONIOENCODING=utf-8 \
    LANG=C.UTF-8 \
    LC_ALL=C.UTF-8

# Install system dependencies
RUN apt-get update && apt-get install -y \
    gcc \
    g++ \
    make \
    libc6-dev \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean

# Create non-root user
RUN groupadd -r scheduler && useradd -r -g scheduler scheduler

# ============================================================================
# Stage 2: Dependencies Installation Layer
# ============================================================================
FROM base as dependencies

# Set working directory
WORKDIR /app

# Copy requirements file
COPY requirements.txt .

# Install Python dependencies
RUN pip install --no-cache-dir --upgrade pip && \
    pip install --no-cache-dir -r requirements.txt

# ============================================================================
# Stage 3: Application Code Layer
# ============================================================================
FROM dependencies as application

# Copy application source code
COPY scheduler_ai/ ./scheduler_ai/
COPY main.py .
COPY run_api.py .

# Create necessary directories
RUN mkdir -p /app/uploads /app/data /app/logs && \
    chown -R scheduler:scheduler /app

# ============================================================================
# Stage 4: Runtime Configuration Layer
# ============================================================================
FROM application as runtime

# Copy startup scripts
COPY docker/start.sh /app/start.sh
COPY docker/health-check.sh /app/health-check.sh

# Make scripts executable
RUN chmod +x /app/start.sh /app/health-check.sh

# Switch to non-root user
USER scheduler

# Expose API port
EXPOSE 8000

# Configure health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
    CMD /app/health-check.sh

# Set default environment variables
ENV API_HOST=0.0.0.0 \
    API_PORT=8000 \
    API_WORKERS=4 \
    MAX_FILE_SIZE=10485760 \
    SOLVER_TIME_LIMIT=300 \
    LOG_LEVEL=INFO

# Default command
CMD ["/app/start.sh"]